package com.scujj.controller.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scujj.controller.GoodsController;
import com.scujj.pojo.Goods;
import com.scujj.pojo.OrderGoods;
import com.scujj.pojo.Result;
import com.scujj.pojo.User;
import com.scujj.service.GoodsService;
import com.scujj.service.OrderGoodsService;
import com.scujj.service.UserService;
import com.scujj.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

import static com.scujj.util.GoodStatusUtil.getGoodStatus;

@RestController
@RequestMapping("/goods")
@Api(tags = "商品api")
@RefreshScope
public class GoodsControllerImpl implements GoodsController {
    @Autowired
    private UserService userService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderGoodsService orderGoodsService;
    @Value("${imgPath.goodsImg}")
    private String imgPath;
    @Value("${staticFilePath}")
    private String rootPath;

    @Override
    @PostMapping("/addGoods")
    @ApiOperation("添加/修改商品")
    @Transactional
    public Result addGoods(@RequestParam(value = "id", required = false) Long id,
                           @RequestParam("name") String name,
                           @RequestParam("number") Integer number,
                           @RequestParam("price") Long price,
                           @RequestParam("describe") String describe,
                           @RequestParam("img") MultipartFile[] imgs,
                           @RequestHeader("token") HashMap<String, String> tokenMap) {
        if (number < 0 || price < 0) {
            return Result.error("参数错误");
        }
        Result result = userService.getUserByToken(tokenMap);
        if (result.getCode() == -1) {
            return result;
        }
        User user = ResultUtil.singleTrans(result.getData(), User.class);
        StringBuilder stringBuilder = new StringBuilder();
        for (MultipartFile img : imgs) {
            String imgName = FileUtil.uploadFile(rootPath + imgPath, img);
            if (imgName == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error("文件上传失败");
            }
            String path = "api-static/" + imgPath + imgName + ";";
            stringBuilder.append(path);
        }
        stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(";"));
        Goods goods = new Goods();
        goods.setId(id).setUid(user.getId()).setName(name).setNumber(number).setPrice(price).setDescribes(describe).setImgSrc(stringBuilder.toString()).setStartTime(new Date());
        goods.setStatus(getGoodStatus(number).status);
        if (goodsService.saveOrUpdate(goods)) {
            return Result.success();
        } else {
            return Result.error("网络错误");
        }
    }


    @Override
    @DeleteMapping("/deleteGoods")
    @ApiOperation("批量删除商品")
    public Result removeGoods(@RequestBody HashMap<String, Object> args) {
        List<Long> idList = (List<Long>) args.get("idList");
        for (Long id : idList) {
            QueryWrapper<Goods> wrapper = new QueryWrapper<>();
            wrapper.eq("id", id).eq("status", GoodStatusUtil.STOP.status);
            if (!goodsService.update(wrapper)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error("网络错误");
            }
        }
        return Result.success();
    }

    @Override
    @PostMapping("/order")
    @ApiOperation("生成订单")
    @Transactional
    public Result orderGoods(@RequestBody HashMap<String, Object> args, @RequestHeader("token") HashMap<String, String> token) {
        Result result = userService.getUserByToken(token);
        if (result.getCode() == -1) {
            return result;
        }
        User user = ResultUtil.singleTrans(result.getData(), User.class);
        Long gid = Long.valueOf((String) args.get("gid"));
        Integer number = (Integer) args.get("number");
        String address = (String) args.get("address");
        if (number < 1) {
            return Result.error("参数错误");
        }
        Goods goods = (Goods) selectGoodsById(gid).getData();
        if (goods == null) {
            return Result.error("参数错误");
        }
        if (Objects.equals(goods.getStatus(), GoodStatusUtil.STOP.status)) {
            return Result.error("商品已停售");
        }
        if (goods.getNumber() < number) {
            return Result.error("库存不足");
        }
        Integer newNumber = goods.getNumber() - number;
        goods.setStatus(GoodStatusUtil.getGoodStatus(newNumber).status);
        goods.setNumber(newNumber);
        if (!goodsService.updateById(goods)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("网络错误");
        }
        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setUid(user.getId()).setGid(gid).setStatus(OrderGoodsStatusUtil.UNPAID.status).
                setMoney(goods.getPrice() * number).setStartTime(new Date()).setGoods(goods).
                setAddress(address).setNumber(number).setUser(user);
        if (orderGoodsService.save(orderGoods)) {
            return Result.success(orderGoods);
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("网络错误");
        }
    }

    @Override
    @GetMapping("/getGoodsByUid")
    @ApiOperation("根据用户id分页查询商品")
    public Result selectGoodsByUid(@RequestParam("id") Long id,
                                   @RequestParam(value = "page", required = false, defaultValue = "1") Long page,
                                   @RequestParam(value = "limit", required = false, defaultValue = "99999") Long limit) {
        Page<Goods> page1 = new Page<>(page, limit);
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.between("status", GoodStatusUtil.ENOUGH.status, GoodStatusUtil.LITTLE.status);
        wrapper.orderByDesc("startTime");
        wrapper.eq("uid", id);
        goodsService.page(page1, wrapper);
        return new PageUtil<Goods>().pageOrder(page1);
    }

    @Override
    @GetMapping("/getGoodsByName")
    @ApiOperation("根据商品名称分页查询商品")
    public Result selectGoodsByName(@RequestParam("name") String name,
                                    @RequestParam(value = "page", required = false, defaultValue = "1") Long page,
                                    @RequestParam(value = "limit", required = false, defaultValue = "99999") Long limit) {
        Page<Goods> page1 = new Page<>(page, limit);
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.between("status", GoodStatusUtil.ENOUGH.status, GoodStatusUtil.LITTLE.status);
        wrapper.orderByDesc("startTime");
        wrapper.like("name", name);
        goodsService.page(page1, wrapper);
        return new PageUtil<Goods>().pageOrder(page1);
    }

    @Override
    @GetMapping("/searchUserGoodsByName")
    @ApiOperation("从个人用户搜索商品")
    public Result searchUserGoodsByName(@RequestParam("name") String name,
                                        @RequestParam("id") Long id,
                                        @RequestParam(value = "page", required = false, defaultValue = "1") Long page,
                                        @RequestParam(value = "limit", required = false, defaultValue = "5") Long limit) {
        Page<Goods> page1 = new Page<>(page, limit);
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.between("status", GoodStatusUtil.ENOUGH.status, GoodStatusUtil.LITTLE.status);
        wrapper.orderByDesc("startTime");
        wrapper.eq("uid", id);
        wrapper.like("name", name);
        goodsService.page(page1, wrapper);
        return new PageUtil<Goods>().pageOrder(page1);
    }


    @Override
    @GetMapping("/getGoodsById")
    @ApiOperation("根据商品id分页查询商品")
    public Result selectGoodsById(@RequestParam("id") Long id) {
        Goods goods = goodsService.getById(id);
        List<Long> ids = new ArrayList<>();
        ids.add(goods.getUid());
        Result result = userService.getUserByIdList(ids);
        if (result.getCode() != 0) {
            return result;
        }
        List<User> userList = ResultUtil.listTrans(result.getData(), User.class);
        if (userList.size() < 1) {
            return Result.error("用户不存在");
        }
        goods.setUser(userList.get(0));
        return Result.success(goods);
    }

    @Override
    @GetMapping()
    @ApiOperation("分页查询所有商品")
    public Result selectAll(@RequestParam("page") Long page, @RequestParam("limit") Long limit) {
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.between("status", GoodStatusUtil.ENOUGH.status, GoodStatusUtil.LITTLE.status);
        wrapper.orderByDesc("startTime");
        Page<Goods> myPage = new Page<>(page, limit);
        goodsService.page(myPage, wrapper);
        return new PageUtil<Goods>().pageOrder(myPage);
    }
}
